package services

import (
	"gitee.com/zhoulvvv/my_go_gateway/dao"
	"github.com/e421083458/golang_common/lib"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"gorm.io/gorm"
)

type ServiceDetailServices struct {
	tx *gorm.DB
}

func NewServiceDetailServices() (*ServiceDetailServices, error) {
	tx, err := lib.GetGormPool("default")
	if err != nil {
		return nil, errors.New("获取数据库连接池失败")
	}
	return &ServiceDetailServices{
		tx: tx,
	}, nil
}

func (sd *ServiceDetailServices) GetServiceDetail(c *gin.Context, serviceInfo *dao.ServiceInfo) (*dao.ServiceDetail, error) {
	// 获取http rule信息
	httpRule := &dao.HttpRule{ServiceId: serviceInfo.Id}
	httpRule, err := httpRule.Find(c, sd.tx, httpRule)
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, errors.New("获取http rule信息失败：" + err.Error())
	}
	// 获取tcp rule信息
	tcpRule := &dao.TcpRule{ServiceId: serviceInfo.Id}
	tcpRule, err = tcpRule.Find(c, sd.tx, tcpRule)
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, errors.New("获取tcp rule信息失败：" + err.Error())
	}
	// 获取grpc rule信息
	grpcRule := &dao.GrpcRule{ServiceId: serviceInfo.Id}
	grpcRule, err = grpcRule.Find(c, sd.tx, grpcRule)
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, errors.New("获取grpc rule信息失败：" + err.Error())
	}
	// 获取loadBalance信息
	loadBalance := &dao.LoadBalance{ServiceId: serviceInfo.Id}
	loadBalance, err = loadBalance.Find(c, sd.tx, loadBalance)
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, errors.New("获取loadBalance信息失败：" + err.Error())
	}
	// 获取accessControl信息
	accessControl := &dao.AccessControl{ServiceId: serviceInfo.Id}
	accessControl, err = accessControl.Find(c, sd.tx, accessControl)
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, errors.New("获取accessControl信息失败：" + err.Error())
	}
	sDetail := &dao.ServiceDetail{
		Info:          serviceInfo,
		HTTPRule:      httpRule,
		TCPRule:       tcpRule,
		GRPCRule:      grpcRule,
		LoadBalance:   loadBalance,
		AccessControl: accessControl,
	}
	return sDetail, nil
}
